package com.alex.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

/**
 * Zookeeper连接
 */
@Slf4j
public class ZookeeperConnection {

    public static void main(String[] args) {
        try {
            CountDownLatch latch = new CountDownLatch(1);
            // zookeeper创建连接是异步的
            // sessionTimeout:session等待时间, 单位是毫秒
            // watch响应事件触发器
            ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 30000, watchedEvent -> {
                log.info("event: {}", watchedEvent);
                if (Watcher.Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                    log.info("Connection...");
                    latch.countDown();
                }

                if (Watcher.Event.KeeperState.Closed == watchedEvent.getState()) {
                    log.info("Closed...");
                }
            });

            latch.await();
            log.info("sessionId: {}", zooKeeper.getSessionId());
            zooKeeper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
